const { Material, Download } = require('../models')
const zipService = require('../utils/zipService')
const progressNotifier = require('../utils/progressNotifier')
const path = require('path')
const fs = require('fs')

// 批量下载
exports.batchDownload = async (req, res) => {
  try {
    const { materialIds } = req.body
    const userId = req.user.id
    
    // 获取资料信息
    const materials = await Material.findAll({
      where: { id: materialIds }
    })

    if (materials.length === 0) {
      return res.status(404).json({
        success: false,
        message: '没有找到可下载的资料'
      })
    }

    // 准备文件列表
    const files = materials.map(material => ({
      path: material.filePath,
      name: `${material.title}${path.extname(material.filePath)}`
    }))

    // 获取客户端ID
    const clientId = req.headers['sec-websocket-key']
    
    // 计算总文件大小
    let totalSize = 0
    for (const file of files) {
      if (fs.existsSync(file.path)) {
        const stats = await fs.stat(file.path)
        totalSize += stats.size
      }
    }

    // 创建进度任务
    const taskId = `task-${Date.now()}-${Math.random().toString(36).substr(2, 8)}`
    progressStore.createTask(taskId, files.length, totalSize)

    // 流式压缩下载
    const archive = archiver('zip', {
      zlib: { level: 5 }
    })

    // 进度事件处理
    let processedFiles = 0
    let processedSize = 0
    archive.on('entry', (entry) => {
      if (entry.stats) {
        processedFiles++
        processedSize += entry.stats.size
        progressStore.updateProgress(taskId, processedFiles, processedSize)
      }
    })

    archive.on('end', () => {
      progressStore.updateProgress(taskId, files.length, totalSize)
    })

    archive.on('error', (err) => {
      const task = progressStore.getProgress(taskId)
      if (task && !task.isCancelled) {
        task.status = 'failed'
        task.updatedAt = Date.now()
      }
    })

    // 设置响应头
    res.attachment('downloads.zip')
    res.setHeader('Content-Type', 'application/zip')
    res.setHeader('X-Task-Id', taskId) // 返回任务ID用于取消
    
    // 处理取消请求
    req.on('close', () => {
      if (!res.headersSent) {
        progressStore.cancelTask(taskId)
      }
    })

    archive.pipe(res)

    // 添加文件
    for (const file of files) {
      if (fs.existsSync(file.path)) {
        const stats = await fs.stat(file.path)
        archive.file(file.path, { 
          name: file.name,
          stats // 传递文件统计信息用于进度计算
        })
      }
    }

    await archive.finalize()

    // 记录下载历史
    await Promise.all(materials.map(material => {
      return Download.create({
        userId,
        materialId: material.id,
        isWatermark: false,
        coinsSpent: material.price,
        ipAddress: req.ip
      })
    }))

    // 更新下载次数
    await Promise.all(materials.map(material => {
      return material.increment('downloads')
    }))

  } catch (error) {
    console.error('批量下载失败:', error)
    res.status(500).json({
      success: false,
      message: '批量下载失败'
    })
  }
}

// 单个文件下载
exports.downloadMaterial = async (req, res) => {
  // 原有单个下载逻辑...
}